// 导入表单验证插件
import validate from 'wechat-validate'
Page({
  data: {
    countDownVisible: true,
    mobile: '13812345678',
    code: '',
    timeData: {}
  },
  // 将插件注入到页面实例中
  behaviors: [validate],
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' }
    ]
  },
  onShow({ redirectURL }) {
    // console.log(router);
    this.redirectURL = redirectURL
  },
  async getSMSCode() {
    // console.log(1);
    // 获取验证结果
    const { valid, message } = this.validate('mobile')
    // console.log(valid, message);
    if (!valid) {
      wx.$toast(message)
      return
    }
    await wx.$http.get('/code', { mobile: this.data.mobile })
    wx.$toast('验证码发送成功!')
    this.setData({ countDownVisible: false })
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 0 && ev.detail.seconds === 0,
    })
  },
  async fromdata() {
    if (!this.validate()) {
      wx.$toast('表单验证失败')
      return
    }
    const { mobile, code } = this.data
    const { token, refreshToken } = await wx.$http.post('/login', { mobile, code })
    // console.log(res);
    const app = getApp()
    app.setToken('token', token)
    app.setToken('refreshToken', refreshToken)
    const url = this.redirectURL || '/pages/profile/index'
    wx.redirectTo({ url })
  }
})
